const tree = {
    /**
     * 过滤树
     * @param treeList 树结构
     * @param func 方法
     */
    treeFilter: (treeList, func) => {
        return treeList.map((node) => ({...node})).filter((node) => {
            node.children = node.children && tree.treeFilter(node.children, func);
            return func(node) || (node.children && node.children.length);
        });
    },

    treeFind: (treeList, func) => {
        for (const data of treeList) {
            if (func(data)) return data;
            if (data.children) {
                const res = tree.treeFind(data.children, func);
                if (res) return res;
            }
        }
        return null;
    },

    buildTree: (data, id, parentId, children) => {
        if (!Array.isArray(data)) {
            console.warn("【Jcx-ui】【tree】传入的必须是一个数组")
            return []
        }
        const config = {
            id: id || "id", parentId: parentId || "parentId", childrenList: children || "children"
        }
        const childrenListMap = {}
        const nodeIds = {}
        const tree = []
        for (const d of data) {
            const parentId = d[config.parentId]
            if (childrenListMap[parentId] == null) {
                childrenListMap[parentId] = []
            }
            nodeIds[d[config.id]] = d
            childrenListMap[parentId].push(d)
        }
        for (const d of data) {
            const parentId = d[config.parentId]
            if (nodeIds[parentId] == null) {
                tree.push(d)
            }
        }
        for (const t of tree) {
            adaptToChildrenList(t)
        }

        function adaptToChildrenList(o) {
            if (childrenListMap[o[config.id]] !== null) {
                o[config.childrenList] = childrenListMap[o[config.id]]
            }
            if (o[config.childrenList]) {
                for (const c of o[config.childrenList]) {
                    adaptToChildrenList(c)
                }
            }
        }

        return tree;
    },

    flattenTree: (tree, idKey = 'id', childrenKey = 'children') => {
        const flattenedList = [];
        const flatten = (node) => {
            // 将当前节点加入到扁平列表中
            const flattenedNode = {...node};
            // 移除子节点，防止循环引用
            delete flattenedNode[childrenKey];
            flattenedList.push(flattenedNode);
            // 递归处理子节点
            if (node[childrenKey] && node[childrenKey].length > 0) {
                for (const child of node[childrenKey]) {
                    flatten(child);
                }
            }
        }
        // 遍历树的根节点，并开始递归处理
        for (const rootNode of tree) {
            flatten(rootNode);
        }
        return flattenedList;
    },

}

export default tree;